var apiHost = wx.getStorageSync("apiHost"); //请求地址
var Appid = wx.getStorageSync('Appid');
var Secret = wx.getStorageSync('Secret');

var AppidFlag = wx.getStorageSync('AppidFlag');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    shopCartHeight : 0, //计算购物车高度
    showFlag : 1,       //编辑购物车商品标识
    shopCartList : '',  //购物车集合
    checkValue:[],      //选中集合
    actualPay:0,        //实付款
    allFlag:'all',      //全选和反选标志
    skuIdCounts : '',   //skuId、数量 集合
    cartId : '',        //购物车id
    editFlag : true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;

    var token = wx.getStorageSync('token');             //用户的token信息
    that.initShopCart(token);                           //初始化购物车
    that.setData({
      token: token
    });
  },
  
  /**
   * 初始化 购物车
   */
  initShopCart: function (token){
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost + "/mobile/users/myshoppingcart", //仅为示例，并非真实的接口地址
      data: {
        token: token,
        appId: AppidFlag
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;
        if (code == "10000") {
          var shopCartList = res.data.data;
          var editFlag = false;

          if (shopCartList.length!=0){
            editFlag = true
            that.shopCartHeight();                              //计算购物车高度
          }
          that.setData({
            shopCartList: shopCartList,
            editFlag: editFlag
          })
          
        } else {
          that.showMsg(msg,'none');
        }
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },

  /**
   * 领取优惠券
   */
  receiveCoupon:function(e){
    var that = this;

    var couponId = e.currentTarget.dataset.couponid;
    var token = that.data.token

    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost + "/mobile/coupon/receive", //仅为示例，并非真实的接口地址
      data: {
        token: token,
        appId: AppidFlag,
        couponId: couponId,
        'type' : 1
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;
        if (code == "10000") {
          that.initShopCart(token); //重新初始化购物车
        } else {
          that.showMsg(msg, 'none');
        }
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },

  //多选
  userCheck: function (e) {
    var that = this;
    let index = e.currentTarget.dataset.id;//获取用户当前选中的索引值
    let checkBox = that.data.shopCartList;
    //全选和反选
    if (index=='all'){
      that.allSelect(checkBox,index,false);
    }else if (index == 'onall') {
      that.allSelect(checkBox, index, true);    
    }else{
      if (checkBox[index].checked) {
        that.data.shopCartList[index].checked = false;
      } else {
        that.data.shopCartList[index].checked = true;
      }
    }

    that.setData({ 
      shopCartList: that.data.shopCartList 
    })

    //返回用户选中的值 (filter过滤器)
    let checkValue = checkBox.filter((checkBox, index) => {
      return checkBox.checked == true;
    })
    
    //选中为空的时候
    if (checkValue.length != 0){
      that.filterSkuCounts(checkValue);
    }else{
      that.setData({
        actualPay : 0,
        checkValue: checkValue,
        skuIdCounts:'',
        cartId:''
      })
    }
  },

  /**
   * 全选和反选
   */
  allSelect: function (checkBox, index,flag){
    var that = this;
    for (var i = 0; checkBox.length > i; i++) {
      that.data.shopCartList[i].checked = flag;
    }
    that.setData({
      allFlag: index
    })
  },

  /**
   * 过滤skuCounts
   */
  filterSkuCounts: function (checkValue){
    var that = this;
    var token = that.data.token;
    
    var skuIdCounts = '';
    var cartId = '';
    for (var i = 0; checkValue.length > i ; i++){
      if(i==0){
        skuIdCounts += checkValue[i].goodsId + ":" + checkValue[i].count;
        cartId += checkValue[i].cartId;
      }else{
        skuIdCounts += ","+ checkValue[i].goodsId + ":" + checkValue[i].count;
        cartId += "," +checkValue[i].cartId;
      }
    }
    that.setData({
      checkValue: checkValue,
      skuIdCounts: skuIdCounts,
      cartId: cartId
    })
    that.calActualMoney(skuIdCounts, token);  //计算实付款
  },

  /**
   * 减少商品数量
   */
  subGoodsNum : function(e){
    var that = this;
    var token = that.data.token;
    var count = e.currentTarget.dataset.count;
    var goodsId = e.currentTarget.dataset.goodsid;

    if (count > 1){
      
      count = parseInt(count) - 1

      //购物车数量的增加和减少
      that.countShopCartNum(token, goodsId, count);
    }

  },

  /**
   * 增加商品数量
   */
  addGoodsNum : function(e){
    var that = this;
    var token = that.data.token;
    var count = e.currentTarget.dataset.count;
    var goodsId = e.currentTarget.dataset.goodsid;

      count = parseInt(count) + 1
      //购物车数量的增加和减少
      that.countShopCartNum(token, goodsId, count);
    
  },

  /**
   * 购物车数量的增加和减少
   */
  countShopCartNum: function (token, goodsId, count){
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost + "/mobile/users/adjustshoppingcartCount", //仅为示例，并非真实的接口地址
      data: {
        token: token,
        appId: AppidFlag,
        goodsId: goodsId,
        count: count,
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;

        if (code == "10000") {
          that.setData({
            actualPay: 0,
            checkValue: [],
            allFlag: 'all'
          })
          that.initShopCart(token); //重新初始化购物车
        } else {
          that.showMsg(msg, 'none');
        }
        wx.hideLoading();           //隐藏加载loading
      }
    })
  },  

  /**
   * 删除购物车项
   */
  delShopCartFlag:function(){
    var that = this;
    var cartId = that.data.cartId;
    var token = that.data.token;
    if (cartId==''){
      that.showMsg('请选择需要删除的商品', 'loading');
    }else{
      that.delshopCart(token,cartId);
    }
  },

  /**
   * 删除购物车商品项（方法）
   */
  delshopCart: function (token,cartId){
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost + "/mobile/users/delshoppingcart", //仅为示例，并非真实的接口地址
      data: {
        token: token,
        appId: AppidFlag,
        cartId: cartId
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;

        if (code == "10000") {
          that.setData({
            actualPay: 0,
            checkValue: [],
            allFlag: 'all'
          })
          that.initShopCart(token); //重新初始化购物车
        } else {
          that.showMsg(msg, 'none');
        }
        wx.hideLoading();           //隐藏加载loading
      }
    })
  },

  /**
   * 计算实付款
   */
  calActualMoney: function (skuIdCounts,token){
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost + "/mobile/orders/calActualMoney", //仅为示例，并非真实的接口地址
      data: {
        token: token,
        appId: AppidFlag,
        skuIdCounts: skuIdCounts,
        isUsePoint: 0,
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;

        if (code == "10000") {
          that.setData({
            actualPay: res.data.data.actualPay
          })

        } else {
          that.showMsg(msg, 'none');
        }
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },

  /**
   * 购物车单项高度
   */
  shopCartHeight: function () {
    var that = this;
    var query = wx.createSelectorQuery();

    var editGoodsConHeight = "";
    var bottomConHeight = "";

    query.select('#editGoodsCon').boundingClientRect()
    query.select('#bottomCon').boundingClientRect()
    query.exec(function (res) {
      editGoodsConHeight = res[0].height;
      bottomConHeight = res[1].height;
      wx.getSystemInfo({
        success: function (res) {
          that.setData({
            shopCartHeight: res.windowHeight - editGoodsConHeight - bottomConHeight
          });
        }
      });
    });
  },

  /**
   * 编辑商品
   */
  editGoods:function(){
    var that = this;
    that.setData({
      showFlag : 0
    })
  },

  /**
   * 完成
   */
  complete: function () {
    var that = this;
    that.setData({
      showFlag: 1
    })
  },

  /**
   * 跳转订单详情
   */
  goFillOrder: function () {
    var that = this;
    var skuIdCounts = that.data.skuIdCounts;
    if (skuIdCounts ==''){
      that.showMsg('请选择结算商品', 'none');
    }else{
      that.setData({
        actualPay: 0,
        checkValue: "",
        skuIdCounts: '',
        cartId: '',
        allFlag: 'all',
      })
      wx.navigateTo({
        url: "../order/fillOrder/fillOrder?skuidcounts=" + skuIdCounts,
      })
    }
  },

  /**
   * 去逛逛跳转
   */
  goIndex:function(){
    wx.switchTab({
      url: '../index/index',
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.onLoad();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  },
  /**
   * 提示信息
   */
  showMsg: function (msg,icon) {
    wx.showToast({
      title: msg,
      icon: icon,
      duration: 2000,
      mask: true
    });
  },
})